import WebAPI from './api.js'
import axios, { AxiosHeaders } from 'axios'
import OS from './OS.js'
import GetUrlImg from './getUrlImg.js'

axios.interceptors.request.use(function (config) {
  let token = OS.GetToken()
  if (token) {
    if (config.headers['Token'] == 'noNeedToken') {
      config.headers['Token'] = null
    } else {
      config.headers['Token'] = token
    }
  }
  return config
}, function (error) {
  return Promise.reject(error)
})

// 请求方法
function request(param = {}) {
  return new Promise((resolve, reject) => {
    axios({
      url: param.url,
      method: param.method,
      data: param.data,
      headers: param.headers
    }).then((res) => {
      // success(res, resolve, reject)
      resolve(res)
    }).catch((err) => {
      reject(err)
    })
  })
}
function get(url, data, headers = {}) {
  return request({
    url: url,
    method: 'get',
    data: data,
    headers: headers
  })
}
function post(url, data, headers = {}) {
  return request({
    url: url,
    method: 'post',
    data: data,
    headers: headers
  })
}
// 成功
function success(res, resolve = () => { }, reject = () => { }) {
  if (res.status == 200) {
    if (res.data && res.data.errorCode == 10000) {
      resolve(res.data.data)
    } else {
      reject(res.data.errMsg)
    }
  } else {
    let msg = handleError(res)
    reject(msg)
  }
}

// 统一错误处理
function handleError(err = {}) {
  let errorCode = err.data.error_code

  return err.data.error_reason

}


let WebRequest = {
  //基础
  GetLibrary: function (Parm) {
    //console.log(WebAPI.GetLibrary, Parm)
    axios({
      method: 'post',
      url: WebAPI.GetLibrary,
      data: {
        pageNum: Parm.page,
        pageSize: Parm.pageSize > 0 ? Parm.pageSize : 20
      }
    }).then((res) => {
      Parm.callback(res)
    })
  },
  UploadImageBase64: function (Parm) {
    //console.log(WebAPI.UploadImage, Parm)
    /*axios({
      method: 'post',
      url: WebAPI.UploadImage,
      data: {
        imageFile: Parm.img
      }
    }).then((res) => {
      Parm.callback(res)
    })*/
    console.log("file:", Parm)
    let parm = new FormData()
    let blob = new Blob([Parm.img], { type: 'image/png' })
    parm.append('imageFile', blob, new Date().getTime() + Math.floor(100000 * Math.random()) + '.png')
    let config = {
      headers: { 'Content-Type': 'multipart/form-data' }
    }
    console.log('upload library image to comfyui parm:', WebAPI.UploadImageToComfyui, parm, config)
    axios.post(WebAPI.UploadImage
      , parm, config)
      .then(res => {
        Parm.callback(res)
      }).catch(res => {
        if (Parm.error != null) {
          Parm.error(res)
        }
      })
  },
  UploadImageToComfyui: function (Parm) {
    let parm = {
      'file': Parm.imageUrl
    }
    let config = {
      headers: { "Token": 'noNeedToken' }
    }
    //console.log('upload library image to comfyui parm:',WebAPI.UploadImageToComfyui,parm,config)
    axios.post(WebAPI.UploadImageToComfyui, parm, config)
      .then(res => {
        Parm.callback(res)
      }).catch(res => {
        Parm.error(res)
      })
  },
  UploadWebImageToOss: function (Parm) {
    console.log("UploadWebImageToOss:", Parm)
    let _parm = new FormData()
    _parm.append('imgUrl', Parm.url)
    let config = {
      headers: { 'Content-Type': 'multipart/form-data' }
    }
    axios.post(WebAPI.UploadWebImageToOss
      , _parm, config)
      .then(res => {
        if (Parm.callback != null) {
          Parm.callback(res)
        } else {
          console.log('UploadWebImageToOss miss callback function')
        }
      }).catch(res => {
        console.log('UploadWebImageToOss error', res)
        if (Parm.error != null) {
          Parm.error(res)
        }
      })
  },

  // 上传图片base64数据到oss
  UploadImageDataToOss: function (Parm) {
    let _parm = new FormData()
    _parm.append('picBase64', Parm.picBase64)
    let config = {
      headers: { 'Content-Type': 'multipart/form-data' }
    }
    axios.post(WebAPI.UploadImageDataToOss, _parm, config)
      .then(res => {
        if (Parm.callback != null) {
          Parm.callback(res)
        } else {
          console.log('UploadImageDataToOss miss callback function')
        }
      }).catch(res => {
        console.log('UploadImageDataToOss error', res)
        if (Parm.error != null) {
          Parm.error(res)
        }
      })
  },

  //功能
  GetMJTaskResult: function (Parm) {
    axios({
      method: 'post',
      url: WebAPI.GetMjResult,
      data: {
        taskId: Parm.taskId
      }
    }).then((res) => {
      Parm.callback(res)
    })
  },
  GetMJSingleResult: function (Parm) {
    axios({
      method: 'post',
      url: WebAPI.GetMjSingleResult,
      data: {
        taskId: Parm.taskId,
        index: Parm.index
      }
    }).then((res) => {
      Parm.callback(res)
    })
  },
  SaveToLibrary: function (Parm) {
    if (Parm.tool == 12 || Parm.tool == 6 || Parm.tool == 1) {
      axios({
        method: 'post',
        url: WebAPI.SaveToLibraryMJ,
        data: {
          taskId: Parm.taskId,//任务ID
          indexList: Parm.indexList//数组，[1,2,3,4]
        }
      }).then((res) => {
        Parm.callback(res)
      })
    } else {
      axios({
        method: 'post',
        url: WebAPI.SaveToLibrary,
        data: {
          id: Parm.taskId,//图库id，更新时必传，新增为空,示例值(1)
          imageURL: Parm.imageURL //图片URL
        }
      }).then((res) => {
        Parm.callback(res)
      })
    }
  },
  //扣费
  //发起消费
  PreConsumerPoint: function (Parm) {
    axios({
      method: 'post',
      url: WebAPI.PreConsumerPoint,
      data: {
        //0, 首页：算力点数; 1 文生图; 2 智能拼图; 3 素材换脸; 4 抠图; 5 高清还原; 6 图片智能二创; 7 涂抹消除; 8 文本消除; 9 扩图重构; 10 换背景; 11 手绘生图12 文生图（MidjourneyBot）,示例值(1)
        serviceType: Parm.serviceType,
        //总像素，原图片长*高,示例值(1000)
        totalPix: Parm.totalPix
      }
    }).then((res) => {
      Parm.callback(res)
    })
  },
  //获取可用剩余算力接口
  GetRediduePoint: function (Parm) {
    axios({
      method: 'post',
      url: WebAPI.GetRediduePoint,
      data: {
        //0, 首页：算力点数; 1 文生图; 2 智能拼图; 3 素材换脸; 4 抠图; 5 高清还原; 6 图片智能二创; 7 涂抹消除; 8 文本消除; 9 扩图重构; 10 换背景; 11 手绘生图12 文生图（MidjourneyBot）,示例值(1)
        serviceType: Parm.serviceType,
        //总像素，原图片长*高,示例值(1000)
        totalPix: Parm.totalPix
      }
    }).then((res) => {
      Parm.callback(res)
    })
  },

  //文生图
  //获取配置文件
  GetSelecterSetting: function (Parm) {
    axios({
      method: 'post',
      url: WebAPI.GetTxt2ImgPromptSelecterSetting,
      data: {
        type: 3
      }
    }).then((res) => {
      Parm.callback(res)
    })
  },
  //发起文生图
  TxtToImg: function (Parm) {
    axios({
      method: 'post',
      url: WebAPI.TxtToImg,
      data: {
        id: Parm.costId,//消费记录ID
        prompt: Parm.basePrompt,//需翻译的中文指令
        promptParam: Parm.optionPrompt,//不需翻译的配置指令
        extendValue: Parm.extendValue//任务的配置参数记录
      }
    }).then((res) => {
      Parm.callback(res)
    }).catch((res) => {
      Parm.error(res);
    })
  },
  //发起图生图
  ImgToImg: function (Parm) {
    axios({
      method: 'post',
      url: WebAPI.TxtToImg,
      data: {
        id: Parm.costId,//消费记录ID
        imageToPromptFlag: Parm.promptFlag,//是否需要图转prompt,示例值(true)	
        ossImgUrls: Parm.imgUrls,//oss图片列表,需要数组格式
        prompt: Parm.basePrompt,//需翻译的中文指令
        promptParam: Parm.optionPrompt,//不需翻译的配置指令
        extendValue: Parm.extendValue,//任务的配置参数记录
        sourceImageDepotId: Parm.sourceImageDepotId//历史图库ID
      }
    }).then((res) => {
      Parm.callback(res)
    }).catch((res) => {
      Parm.error(res);
    })
  },
  RemoveBackground: function (Parm) {
    axios({
      method: 'post',
      url: WebAPI.RemoveBackground,
      data: {
        id: Parm.costId,//消费记录ID
        imgUrl: Parm.imgUrl,//oss图片列表
        sourceImageDepotId: Parm.sourceImageDepotId,//历史图库ID
        extendValue: Parm.extendValue//任务的配置参数记录
      }
    }).then((res) => {
      Parm.callback(res)
    }).catch((res) => {
      Parm.error(res);
    })
  },
  ReplaceBackground: function (Parm) {
    axios({
      method: 'post',
      url: WebAPI.ReplaceBackground,
      data: {
        id: Parm.costId,//消费记录ID
        imgUrl: Parm.imgUrl,//oss图片列表
        prompt: Parm.basePrompt,//需翻译的中文指令
        promptParam: Parm.optionPrompt,//不需翻译的配置指令
        extendValue: Parm.extendValue,
        sourceImageDepotId: Parm.sourceImageDepotId//历史图库ID
      }
    }).then((res) => {
      Parm.callback(res)
    }).catch((res) => {
      Parm.error(res);
    })
  },
  Upscaling: function (Parm) {
    console.log(Parm)
    var targetH = 0;
    var targetW = 0;
    var setSize = function (_w, _h) {
      //console.log(_w,_h)
      var __w = _w
      var __h = _h
      if (_w > _h) {
        __w = 4000;
        __h = Math.floor(_h * 4000 / _w)
      } else {
        __h = 4000
        __w = Math.floor(_w * 4000 / _h)
      }
      targetH = __h
      targetW = __w
      //console.log(targetW,targetH)
    }
    var post = function () {
      axios({
        method: 'post',
        url: WebAPI.Upscaling,
        data: {
          id: Parm.costId,//消费记录ID
          imgUrl: Parm.imgUrl,//oss图片列表
          targetHeight: targetH,
          targetWidth: targetW,
          extendValue: Parm.extendValue,
          sourceImageDepotId: Parm.sourceImageDepotId//历史图库ID
        }
      }).then((res) => {
        Parm.callback(res)
      }).catch((res) => {
        Parm.error(res);
      })
    }
    var img = new Image();
    img.src = Parm.imgUrl;
    if (img.complete) {
      setSize(img.width, img.height)
      post()
    } else {
      img.onload = function () {
        setSize(img.width, img.height)
        post()
        img.onload = null
      }
    }
  },
  //模特换装
  //服装抠图
  SegmentCloth: function (Parm) {
    //console.log(Parm)
    axios({
      method: 'post',
      url: WebAPI.SegmentCloth,
      data: {
        clothClass: Parm.clothClass,
        imageURL: Parm.imageURL,
        returnForm: Parm.returnForm
      }
    }).then((res) => {
      Parm.callback(res)
    }).catch((res) => {
      Parm.error(res)
    })
  },
  //换装
  ModelSwap: function (Parm) {
    let parm = {
      maskImage: Parm.maskImage,
      originalImage: Parm.originalImage,
      prompt: Parm.prompt,
      negativePrompt: Parm.negativePrompt
    }
    let config = {
      headers: { "Token": 'noNeedToken' }
    }
    axios.post(WebAPI.ModelSwap, parm, config)
      .then(res => {
        Parm.callback(res)
      }).catch(res => {
        Parm.error(res)
      })
  },
  //获取ComfyUI结果文件名
  GetComfyuiFileName: function (Parm) {
    let parm = {
      promptId: Parm.promptId,
    }
    let config = {
      headers: { "Token": 'noNeedToken' }
    }
    axios.post(WebAPI.GetComfyuiFileName, parm, config)
      .then(res => {
        Parm.callback(res)
      }).catch(res => {
        Parm.error(res)
      })
  },
  //获取ComfyUI结果URL
  GetComfyuiFileUrl: function (Parm) {
    let parm = {
      fileName: Parm.fileName,
    }
    let config = {
      headers: { "Token": 'noNeedToken' }
    }
    axios.post(WebAPI.GetComfyuiFileUrl, parm, config)
      .then(res => {
        Parm.callback(res)
      }).catch(res => {
        Parm.error(res)
      })
  },
  //换脸
  SwapFace: {
    UploadTemplate: function (Parm) {
      axios({
        method: 'post',
        url: WebAPI.UploadTemplate,
        data: {
          imageURL: Parm.imgUrl//oss图片列表
        }
      }).then((res) => {
        Parm.callback(res)
      }).catch((res) => {
        Parm.error(res);
      })
    },
    MergeImage: function (Parm) {
      axios({
        method: 'post',
        url: WebAPI.MergeImage,
        data: {
          id: Parm.costId,//消费记录ID
          imageURL: Parm.imgUrl,//脸图
          templateId: Parm.templateId,//模特图模板ID
          sourceImageDepotId: Parm.sourceImageDepotId,//历史图库ID
          extendValue: Parm.extendValue,
        }
      }).then((res) => {
        Parm.callback(res)
      }).catch((res) => {
        Parm.error(res);
      })
    }
  },
  Fooocus: {
    expand: (data = {}) => {
      console.log(data, WebAPI.Fooocus.expand);
      return axios({
        method: 'post',
        url: '/fooocus/extend/',
        // url: "http://192.168.0.14:9809/fooocus/expand/",
        data
      })
    },
  },
  // 莉莉丝
  Lili: {
    token: localStorage.getItem('Admin-Token') || null,
    getConfig: (headers = {}) => {
      return {
        headers: {
          'Access-Token': WebRequest.Lili.token,
          ...headers
        }
      }
    },
    /** 发送短信
     * data: {
     *   mobile: '12580123123',
     *   type: 1
     * }
     */
    SendSmsCode: (data = {}) => {
      return axios({ method: 'post', url: WebAPI.Lili.SendSmsCode, data })
    },
    /** 发送短信
  * data: {
  *   mobile: '12580123123',
  *   type: 1
  * }
  */
    People: (data = {}) => {
      return axios({
        method: 'get',
        url: WebAPI.Lili.People,
        headers: {
          Authorization: "Bearer r-hVWNBmb39aNZtBq7mtqUjqXTwxkMHc_1701051794"
        }
      })
    },
    AddChat: (data = {}) => {
      const url = `${WebAPI.Lili.AddChat}`;
      console.log(data, 'data');
      return axios({
        method: 'post', // 使用 POST 方法
        url: url,
        data: { // 设置请求的正文数据
          people_id: data
        },
        headers: {
          Authorization: "Bearer r-hVWNBmb39aNZtBq7mtqUjqXTwxkMHc_1701051794",
          'Content-Type': 'application/json' // 设置请求正文的类型为 JSON
        }
      });
    },

    /** 登录
     * data: {
     *   code: Parm.code,
     *   mobile: Parm.mobile,
     * }
     */
    Login: (data = {}) => {
      return axios({ method: 'post', url: WebAPI.Lili.Login, data })
    },
    /** 提交机器人ID，获取机器人
     * data: {
     *   id: 52
     * },
     */
    getView: (data = {}, headers = {}) => {
      let config = WebRequest.Lili.getConfig(headers)
      return axios.get(`${WebAPI.Lili.View}?id=${data.id}`, data, config)
    },
    /** 获取机器人对话列表
     * data: {
     *   chat_id: 0,
     *   model_id: '52'
     * },
     */
    getChatPeople: (data = {}, headers = {}) => {
      let config = WebRequest.Lili.getConfig(headers)
      return axios.post(WebAPI.Lili.ChatPeople, data, config)
    },
    // 发起聊天
    /**
     * data: { 
        chat_id: '1710148516',
        prompt: '西瓜帽的制作方法',
        image_action: '',
        image_index: 0,
        image_task_id: 0,
        image_url: '',
        model_id: 52,
        type: 1,
        use_model: 3
     }
     */
    postChat: (data = {}, headers = {}) => {
      let config = WebRequest.Lili.getConfig(headers)
      return axios.post(WebAPI.Lili.Chat, data, config)
    },
    /** 获取 session_id
     * data: {
     *   session_id: Parm.session_id
     * }
     */
    getAnswer: (data = {}, headers = {}) => {
      let config = WebRequest.Lili.getConfig(headers)
      return axios.get(`${WebAPI.Lili.Answer}?session_id=${data.session_id}`, data, config)
    },
    /** 清除聊天，开始新对话
     * data: {
     *   chat_id: "1708777980"
     * }
     */
    Clear: (data = {}, headers = {}) => {
      let config = WebRequest.Lili.getConfig(headers)
      return axios.post(WebAPI.Lili.Clear, data, config)
    },
  },

  // 阿里接口
  ALi: {
    // 交互式全分割
    InteractiveFullSegmentation: (data = {}) => {
      return post(WebAPI.ALi.InteractiveFullSegmentation, data)
    },
    // 互动涂鸦分割
    InteractiveScribbleSegmentation: (data = {}, headers = {}) => {
      return post(WebAPI.ALi.InteractiveScribbleSegmentation, data)
    },
    // 获取异步任务结果
    getJobResult: (data = {}, headers = {}) => {
      return post(WebAPI.ALi.GetJobResult, data)
    },
    SegmentCloth: (data = {}, headers = {}) => {
      return post(WebAPI.ALi.SegmentCloth, data)
    },
  },

  ComfyUi: {
    // 上传图片：支持文件流、支持图片url
    UploadImage: (data = {}, headers = {}) => {
      return post(WebAPI.ComfyUi.UploadImage, data)
    },

    // 换模特换背景
    ChangeModelBackgroundImage: (data = {}, headers = {}) => {
      return post(WebAPI.ComfyUi.ChangeModelBackgroundImage, data)
    },

    // 下载图片
    /**
     * data: {
     *  fileName: "ComfyUI_00017_.png" 
     * }
    */
    DownloadImage: (data = {}, headers = {}) => {
      return post(WebAPI.ComfyUi.DownloadImage, data)
    },

    // 下载图片
    /**
     * data: {
     *  fileName: "ComfyUI_00017_.png" 
     * }
    */
    DownloadImage: (data = {}, headers = {}) => {
      return post(WebAPI.ComfyUi.DownloadImage, data)
    },

    // getDataBySync: (data = {}, headers = {}) => {
    //   console.log(data);
    //   return post(WebAPI.ComfyUi.DownloadImage, data)
    // },
    getDataBySync: (data = {}) => {
      const url = `${WebAPI.ComfyUi.getDataBySync}`;
      console.log(data, 'data');
      return axios({
        method: 'post', // 使用 POST 方法
        url: url,
        data
      });
    },
  },

  Image: {
    // 获取模特图
    getModel: (data = {}, headers = {}) => {
      return get(WebAPI.Image.getModel, data)
    },
    /** 根据分组ID获取模特图片
     * data: {
     *  categoryId: 001
     * }
    */
    getModelByCategoryId: (data = {}, headers = {}) => {
      return get(WebAPI.Image.getModelByCategoryId, data)
    },
    // 获取模特风格图
    getModelGroup: (data = {}, headers = {}) => {
      return get(WebAPI.Image.getModelGroup, data)
    },
    /** 根据分组ID获取模特图片
     * data: {
     *  modelGroupId: 001
     * }
    */
    // 根据分组ID获取模特风格图
    getModelGroupByGroupId: (data = {}, headers = {}) => {
      return get(WebAPI.Image.getModelGroupByGroupId, data)
    },
    // 获取场景图
    getScene: (data = {}, headers = {}) => {
      return get(WebAPI.Image.getScene, data)
    },
  }

}

export default WebRequest
